#include "DoublyLinkedList.h"

#ifdef __cplusplus
extern "C"
{
#endif

DLL_Element *DLL_AppendElement(DLL_Element *One, DLL_Element *Two)
{
	Two->Next = NULL;
	One->Next = Two;
	Two->Previous = One;
	return One;
}

DLL_Element *DLL_InsertElement(DLL_Element *One, DLL_Element *Two)
{
	DLL_Element *TempPointer = One->Next;
	Two->Previous = One;
	One->Next = Two;
	Two->Next = TempPointer;
	TempPointer->Previous = Two;
	return One;
}

DLL_Element *DLL_GetNthElementFrom(DLL_Element *From, int N)
{
	int X;
	DLL_Element *TempPointer = From;
	for(X = 0; X < N; ++X)
	{
		TempPointer = TempPointer->Next;
		if(TempPointer == NULL)
			return NULL;
	}
	return TempPointer;
}

DLL_Element *DLL_GetNthElementBefore(DLL_Element *Before, int N)
{
	int X;
	DLL_Element *TempPointer = Before;
	for(X = 0; X < N; ++X)
	{
		TempPointer = TempPointer->Previous;
		if(TempPointer == NULL)
			return NULL;
	}
	return TempPointer;
}

int DLL_GetSizeFrom(DLL_Element *From)
{
	int Size;
	DLL_Element *TempPointer;
	for(TempPointer = From, Size = 0;
		TempPointer->Next != NULL;
		TempPointer = TempPointer->Next, ++Size);
	return Size + 1;
}

int DLL_GetSizeBefore(DLL_Element *Before)
{
	int Size;
	DLL_Element *TempPointer;
	for(TempPointer = Before, Size = 0;
		TempPointer->Previous != NULL;	
		TempPointer = TempPointer->Previous, ++Size);
	return Size + 1;
}

DLL_Element *DLL_RemoveElementsBetween(DLL_Element *One, DLL_Element *Two)
{
	One->Next = Two;
	Two->Previous = One;
	return One;
}

DLL_Element *DLL_AppendList(DLL_Element *ListOne, DLL_Element *ListTwo)
{
	ListOne->Next = ListTwo;
	ListTwo->Previous = ListOne;
	return ListOne;
}

DLL_Element *DLL_InsertList(DLL_Element *At, DLL_Element *List)
{
	DLL_Element *TempPointer = At->Next;
	At->Next = List;
	List->Previous = At;
	while(List->Next != NULL)
		List = List->Next;
	List->Next = TempPointer;
	TempPointer->Previous = List;
	return At;
}

DLL_Element *DLL_GetFirstElement(DLL_Element *Element)
{
	while(Element->Previous != NULL)
		Element = Element->Previous;
	return Element;
}
DLL_Element *DLL_GetLastElement(DLL_Element *Element)
{
	while(Element->Next != NULL)
		Element = Element->Next;
	return Element;
}

DLL_Element *DLL_Swap(DLL_Element *A, DLL_Element *B)
{
	DLL_Element *TempPointer = A->Next;
	A->Next = B->Next;
	B->Next = TempPointer;
	TempPointer = A->Previous;
	A->Previous = B->Previous;
	B->Previous = TempPointer;
	return A;
}

#ifdef __cplusplus
}
#endif
